<?php

namespace app\v1\controller;
use support\Request;
use support\Response;
use app\model\CityModel;
use app\model\CardUserModel;
use app\model\CardModel;
use app\model\CardItemModel;
use app\model\CardTopicOrderModel;
use EasyWeChat\Factory;
use Exception;
use support\Db;
use support\Log;
use app\model\UserModel;
use app\model\ScoreLogModel;
use app\model\CompanyModel;

class CardController {
    
    /**
     * 获取当前用户绑定的所有卡片（分页）
     * 
     * @param Request $request
     * @return Response
     */
    public function index(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            
            $userId = $user['id'];
            
            // 获取分页参数
            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('page_size', 10);
            


            // 查询用户绑定的卡片，关联卡片和卡片项信息
            $cardUsers = CardUserModel::select([
                'card_user.*',
                'card.name as card_name',
                'card.image as card_image',
                'card.score as card_score',
                'card_item.card_no',
                'card_item.card_number',
                'card.company_id',
                'card.type'
            ])
            ->leftJoin('card', 'card_user.card_id', '=', 'card.id')
            ->leftJoin('card_item', 'card_user.card_item_id', '=', 'card_item.id')
            ->where('card_user.user_id', $userId)
            ->orderBy('card_user.score', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
            
            // 处理返回数据，添加状态文本等信息
            $items = $cardUsers->items();
            foreach ($items as &$item) {
                // 添加卡片项状态文本
                if (isset($item->status)) {
                    $item->status_text = CardUserModel::getStatusText($item->status);
                }
                
                // 计算是否过期
                if (isset($item->expired_at) && $item->expired_at > 0) {
                    $item->is_expired = time() > $item->expired_at;
                } else {
                    $item->is_expired = false;
                }
                
                // 格式化时间
                if (isset($item->created_at)) {
                    $item->created_at_text = date('Y-m-d H:i:s', $item->created_at);
                }
                if (isset($item->expired_at) && $item->expired_at > 0) {
                    $item->expired_at_text = date('Y-m-d', $item->expired_at);
                }

                $item['score'] = round($item->score, 2);

                if($item->type == 'company'){
                    $item['company'] = CompanyModel::find($item->company_id);
                }
            }
            
            return json([
                'data' => [
                    'list' => $items,
                    'total' => $cardUsers->total(),
                    'current_page' => $cardUsers->currentPage(),
                    'per_page' => $cardUsers->perPage(),
                    'last_page' => $cardUsers->lastPage()
                ],
                'msg' => '获取卡片列表成功',
                'code' => 1
            ]);
            
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取卡片详情
     * 
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            
            $userId = $user['id'];
            $cardUserId = $request->get('id');
            
            if (empty($cardUserId)) {
                throw new Exception('卡片ID不能为空');
            }
            
            // 查询用户绑定的卡片详情
            $cardUser = CardUserModel::select([
                'card_user.*',
                'card.name as card_name',
                'card.image as card_image',
                'card.score as card_score',
                'card.expired_days as card_expired_days',
                'card_item.card_no',
                'card_item.card_number',
                'card_item.status as card_item_status',
                'card_item.expired_days as card_item_expired_days'
            ])
            ->leftJoin('card', 'card_user.card_id', '=', 'card.id')
            ->leftJoin('card_item', 'card_user.card_item_id', '=', 'card_item.id')
            ->where('card_user.id', $cardUserId)
            ->where('card_user.user_id', $userId)
            ->first();
            
            if (!$cardUser) {
                throw new Exception('卡片不存在或无权限访问');
            }
            
            // 处理返回数据
            $cardUser->card_item_status_text = CardItemModel::getStatusText($cardUser->card_item_status);
            $cardUser->status_text = CardUserModel::getStatusText($cardUser->status);
            
            // 计算是否过期
            $cardUser->is_expired = false;
            if ($cardUser->expired_at > 0) {
                $cardUser->is_expired = time() > $cardUser->expired_at;
            }
            
            // 格式化时间
            if ($cardUser->created_at) {
                $cardUser->created_at_text = date('Y-m-d H:i:s', $cardUser->created_at);
            }
            if ($cardUser->expired_at > 0) {
                $cardUser->expired_at_text = date('Y-m-d H:i:s', $cardUser->expired_at);
            }
            
            return json([
                'data' => $cardUser,
                'msg' => '获取卡片详情成功',
                'code' => 1
            ]);
            
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
    

    /**
     * 绑定卡片
     * 
     * @param Request $request
     * @return Response
     */
    public function bind(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            
            $userId = $user['id'];
            $input = $request->post('data');
            $cardNumber = $input['card_number'];
            
            
            if (empty($cardNumber)) {
                throw new Exception('卡密不能为空');
            }
            
            // 查询卡片项
            $cardItem = CardItemModel::where('card_number','=', $cardNumber)
                ->where('status', CardItemModel::STATUS_INACTIVE)
                ->first();
            
            if (!$cardItem) {
                throw new Exception('卡密错误，或卡片已被使用');
            }
            
            // 检查用户是否已经绑定过这张卡片
            $existingBind = CardUserModel::where('user_id', $userId)
                ->where('card_item_id', $cardItem->id)
                ->where('status', CardUserModel::STATUS_USED)
                ->first();
            
            if ($existingBind) {
                throw new Exception('您已经绑定过这张卡片');
            }
            
            // 查询卡片信息
            $card = CardModel::find($cardItem->card_id);
            if (!$card) {
                throw new Exception('卡片信息不存在');
            }
            
            // 开始事务
            \support\Db::beginTransaction();
            
            try {
                // 创建用户卡片绑定记录
                $cardUser = new CardUserModel();
                $cardUser->user_id = $userId;
                $cardUser->card_id = $cardItem->card_id;
                $cardUser->card_item_id = $cardItem->id;
                $cardUser->status = CardUserModel::STATUS_USED;
                $cardUser->score = $cardItem->score;
                $cardUser->created_at = time();
                $cardUser->updated_at = time();
                $cardUser->phone = $user->phone;
                
                // 设置过期时间
                $currentTime = time();
                if ($cardItem->expired_days > 0) {
                    $cardUser->expired_at = $currentTime + ($cardItem->expired_days * 86400); // 86400 = 24*60*60
                } elseif ($card->expired_days > 0) {
                    $cardUser->expired_at = $currentTime + ($card->expired_days * 86400);
                } else {
                    $cardUser->expired_at = 0; // 永不过期
                }
                
                $cardUser->save();
                
                // 更新卡片项状态为已使用
                $cardItem->status = CardItemModel::STATUS_ACTIVE;
                $cardItem->updated_at = time();
                $cardItem->save();

                if(empty($user->company_id)){
                    $user->company_id = $card->company_id;
                    $user->save();
                }
                
                \support\Db::commit();
                
                return json([
                    'data' => [
                        'card_user_id' => $cardUser->id,
                        'card_name' => $card->name,
                        'score' => $cardItem->score
                    ],
                    'msg' => '绑定成功',
                    'code' => 1
                ]);
                
            } catch (Exception $e) {
                \support\Db::rollback();
                throw $e;
            }
            
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取当前登录用户所有有效的卡片（未过期且积分大于0）
     * 
     * @param Request $request
     * @return Response
     */
    public function getValidCards(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            
            $userId = $user['id'];
            $currentTime = time();
            
            // 查询用户所有有效的卡片（未过期且积分大于0）
            $validCards = CardUserModel::select([
                'card_user.*',
                'card.name as card_name',
                'card.image as card_image',
                'card.score as card_score',
                'card_item.card_no',
                'card_item.status as card_item_status'
            ])
            ->leftJoin('card', 'card_user.card_id', '=', 'card.id')
            ->leftJoin('card_item', 'card_user.card_item_id', '=', 'card_item.id')
            ->where('card_user.user_id', $userId)
            ->where('card_user.status', CardUserModel::STATUS_USED)
            ->where('card_user.score', '>', 0)
            ->where(function($query) use ($currentTime) {
                $query->where('card_user.expired_at', 0)  // 永不过期
                      ->orWhere('card_user.expired_at', '>', $currentTime); // 未过期
            })
            ->orderBy('card_user.expired_at', 'asc')
            ->get();
            
            // 处理返回数据，添加状态文本等信息
            $items = [];
            foreach ($validCards as $item) {
                $cardData = [
                    'id' => $item->id,
                    'card_name' => $item->card_name,
                    'card_image' => $item->card_image,
                    'card_no' => $item->card_no,
                    'score' => (float)$item->score,
                    'card_item_status' => $item->card_item_status,
                    'card_item_status_text' => CardItemModel::getStatusText($item->card_item_status),
                    'created_at' => $item->created_at,
                    'created_at_text' => date('Y-m-d H:i:s', $item->created_at),
                    'expired_at' => $item->expired_at,
                    'is_expired' => false
                ];
                
                // 格式化过期时间
                if ($item->expired_at > 0) {
                    $cardData['expired_at_text'] = date('Y-m-d', $item->expired_at);
                } else {
                    $cardData['expired_at_text'] = '永不过期';
                }
                
                $items[] = $cardData;
            }
            
            return json([
                'data' => [
                    'list' => $items,
                    'total' => count($items)
                ],
                'msg' => '获取有效卡片列表成功',
                'code' => 1
            ]);
            
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function topics(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            $page = (int)$request->get('page', 1);
            $pageSize = (int)$request->get('page_size', 10);

            $query = CardModel::where('type', '=','topic')
                ->orderBy('sort_by', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            $items = $query->items();

            $prices = config('site.topic_card_money_list');

            return json([
                'data' => [
                    'list' => $items,
                    'total' => $query->total(),
                    'current_page' => $query->currentPage(),
                    'per_page' => $query->perPage(),
                    'last_page' => $query->lastPage(),
                    'prices' => $prices
                ],
                'msg' => '获取话题列表成功',
                'code' => 1
            ]);
        }catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function allTopics(Request $request): Response
    {
        try {
            
            $items = CardModel::where('type', '=','topic')
                ->orderBy('sort_by', 'desc')
                ->get();

            foreach ($items as &$item) {
                
            }

            return json([
                'data' => $items,
                'msg' => '获取话题列表成功',
                'code' => 1
            ]);
        }catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 购买主题卡
     * 
     * @param Request $request
     * @return Response
     */
    public function buyTopic(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            
            $userId = $user['id'];
            $input = $request->post('data');
            $cardId = $input['card_id'];
            $price = $input['price'];
            
            if (empty($cardId)) {
                throw new Exception('卡片ID不能为空');
            }

            if(empty($price)){
                throw new Exception('面额不能为空');
            }
            
            // 查询主题卡信息
            $card = CardModel::where('id', $cardId)
                ->where('type', 'topic')
                ->first();
            
            if (!$card) {
                throw new Exception('主题卡不存在');
            }
            
            // 开始事务
            Db::beginTransaction();
            
            try {
                // 创建主题卡订单记录
                $order = new CardTopicOrderModel();
                $order->user_id = $userId;
                $order->card_id = $cardId;
                $order->price = $price;
                $order->money = $price;
                $order->status = 'unpay';
                
                $order->created_at = time();
                $order->updated_at = time();
                $order->save();
                
                // 生成微信支付订单
                $app = Factory::payment(config('wechat.mini_app'));
                
                $outTradeNo = 'CTO' . date('YmdHis') . $order->id;
                $result = $app->order->unify([
                    'body' => '主题卡购买：' . $card->name,
                    'out_trade_no' => $outTradeNo,
                    'total_fee' => $order->money * 100, // 微信支付金额单位为分
                    'trade_type' => 'JSAPI',
                    'notify_url' => config('site.site_url') . "/v1/card/topic-notify",
                    'openid' => $user['open_id']
                ]);

                if ($result['return_code'] !== 'SUCCESS' || $result['result_code'] !== 'SUCCESS') {
                    throw new Exception('微信支付订单创建失败：' . ($result['err_code_des'] ?? $result['return_msg']));
                }

                // 更新订单记录
                $order->out_trade_no = $outTradeNo;
                $order->save();

                Db::commit();

                // 生成支付签名
                $paySign = $app->jssdk->bridgeConfig($result['prepay_id'], false);
                
                return json([
                    'data' => [
                        'order_id' => $order->id,
                        'card_name' => $card->name,
                        'price' => $price,
                        'prepay_id' => $result['prepay_id'],
                        'timeStamp' => $paySign['timeStamp'],
                        'nonceStr' => $paySign['nonceStr'],
                        'package' => $paySign['package'],
                        'signType' => $paySign['signType'],
                        'paySign' => $paySign['paySign']
                    ],
                    'msg' => '订单创建成功',
                    'code' => 1
                ]);
                
            } catch (Exception $e) {
                Db::rollback();
                throw $e;
            }
            
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 主题卡购买微信支付回调通知
     * 
     * @param Request $request
     * @return Response
     */
    public function topicNotify(Request $request): Response
    {
        try {
            $app = Factory::payment(config('wechat.mini_app'));
            $response = $app->handlePaidNotify(function ($message, $fail) {
                // 查询订单记录
                
                $outTradeNo = $message['out_trade_no'];
                $order = CardTopicOrderModel::where('out_trade_no', $outTradeNo)->first();
                
                if (!$order) {
                    return $fail('订单记录不存在');
                }

                if ($order->status == 'pay') {
                    return true; // 已经处理过了
                }

                // 验证支付状态
                if ($message['result_code'] !== 'SUCCESS') {
                    $order->status = 'fail'; // 支付失败
                    $order->save();
                    return $fail('支付失败');
                }

                // 开始事务
                Db::beginTransaction();

                try {
                    // 更新订单状态
                    $order->status = 'pay';
                    $order->paid_at = time();
                    $order->transaction_id = $message['transaction_id'];
                    $order->save();

                    // 查询卡片信息
                    $card = CardModel::find($order->card_id);
                    if (!$card) {
                        throw new Exception('卡片信息不存在');
                    }

                    // 生成卡片项
                    $cardItem = new CardItemModel();
                    $cardItem->card_id = $order->card_id;
                    $cardItem->card_number = CardItemModel::generateCardNumber();
                    $cardItem->card_no = CardItemModel::generateCardNo();
                    $cardItem->status = CardItemModel::STATUS_ACTIVE;
                    $cardItem->expired_days = $card->expired_days;
                    $cardItem->score = $order->price;
                    $cardItem->created_at = time();
                    $cardItem->updated_at = time();
                    $cardItem->save();

                    // 创建用户卡片绑定记录
                    $cardUser = new CardUserModel();
                    $cardUser->user_id = $order->user_id;
                    $cardUser->card_id = $order->card_id;
                    $cardUser->card_item_id = $cardItem->id;
                    $cardUser->status = CardUserModel::STATUS_UNUSED;
                    $cardUser->score = $order->price;
                    $cardUser->created_at = time();
                    $cardUser->updated_at = time();
                    $cardUser->phone = $order->user->phone ?? '';
                    $cardUser->type = 'topic';
                    $cardUser->topic_order_id = $order->id;
                    $cardUser->source_user_id = 0;
                    
                    // 设置过期时间
                    $currentTime = time();
                    if ($card->expired_days > 0) {
                        $cardUser->expired_at = $currentTime + ($card->expired_days * 86400);
                    } else {
                        $cardUser->expired_at = 0; // 永不过期
                    }
                    
                    $cardUser->save();

                    Db::commit();
                    return true;
                } catch (Exception $e) {
                    Db::rollBack();
                    return $fail('处理失败：' . $e->getMessage());
                }
            });

           
            return response('fail');
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 查询主题卡订单状态
     * 
     * @param Request $request
     * @return Response
     */
    public function topicOrderStatus(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }

            $orderId = $request->get('order_id');
            if (empty($orderId)) {
                throw new Exception('订单ID不能为空');
            }

            $order = CardTopicOrderModel::where('id', $orderId)
                ->where('user_id', $user['id'])
                ->first();

            if (!$order) {
                throw new Exception('订单不存在');
            }

            return json([
                'data' => [
                    'order_id' => $order->id,
                    'card_id' => $order->card_id,
                    'price' => $order->price,
                    'money' => $order->money,
                    'status' => $order->status,
                    'status_text' => $this->getTopicOrderStatusText($order->status),
                    'created_at' => $order->created_at,
                    'paid_at' => $order->paid_at
                ],
                'msg' => '查询成功',
                'code' => 1
            ]);
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    /**
     * 获取主题卡订单状态文本
     * 
     * @param string $status
     * @return string
     */
    private function getTopicOrderStatusText($status): string
    {
        switch ($status) {
            case 'unpay':
                return '待支付';
            case 'pay':
                return '已支付';
            case 'fail':
                return '支付失败';
            default:
                return '未知状态';
        }
    }

    /**
     * 转赠卡片
     * 
     * @param Request $request
     * @return Response
     */
    public function transferCard(Request $request): Response
    {
        try {
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            
            $userId = $user['id'];
            $input = $request->post('data');
            $cardUserId = $input['card_user_id'];
            $targetPhone = $input['target_phone'];
            
            if (empty($cardUserId)) {
                throw new Exception('卡片ID不能为空');
            }
            
            if (empty($targetPhone)) {
                throw new Exception('目标手机号不能为空');
            }
            
            // 验证手机号格式
            if (!preg_match('/^1[3-9]\d{9}$/', $targetPhone)) {
                throw new Exception('手机号格式不正确');
            }
            
            // 查询要转赠的卡片
            $cardUser = CardUserModel::where('id', $cardUserId)
                ->where('user_id', $userId)
                ->where('type','=','topic')
                ->where('status', CardUserModel::STATUS_UNUSED)
                ->first();
            
            if (!$cardUser) {
                throw new Exception('卡片不存在或无权限转赠');
            }
            
            // 检查卡片是否过期
            if ($cardUser->expired_at > 0 && $cardUser->expired_at < time()) {
                throw new Exception('卡片已过期，无法转赠');
            }
            
            // 检查卡片积分是否大于0
            if ($cardUser->score <= 0) {
                throw new Exception('卡片积分不足，无法转赠');
            }

            if($cardUser->source_user_id > 0){
                throw new Exception('该卡片已转赠，无法再次转赠');
            }
            
            // 根据手机号查找目标用户
            $targetUser = UserModel::where('phone', $targetPhone)->first();
            
            if (!$targetUser) {
                throw new Exception('该手机号不是会员，无法转赠');
            }
            
            // 不能转赠给自己
            if ($targetUser->id == $userId) {
                throw new Exception('不能转赠给自己');
            }
            
            // 开始事务
            Db::beginTransaction();
            
            try {
                // 更新卡片用户ID
                $cardUser->user_id = $targetUser->id;
                $cardUser->source_user_id = $userId;
                $cardUser->phone = $targetUser->phone;
                $cardUser->updated_at = time();
                $cardUser->save();
                
                Db::commit();
                
                return json([
                    'data' => [
                        'card_user_id' => $cardUser->id,
                        'target_user_id' => $targetUser->id,
                        'target_phone' => $targetPhone
                    ],
                    'msg' => '转赠成功',
                    'code' => 1
                ]);
                
            } catch (Exception $e) {
                Db::rollback();
                throw $e;
            }
            
        } catch (Exception $e) {
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }

    public function logs(Request $request){
        try{
            $user = $request->userLogin;
            if (empty($user) || empty($user['id'])) {
                throw new Exception('用户未登录');
            }
            $userId = $user['id'];
            $page = $request->get('page', 1);
            $pageSize = $request->get('page_size', 10);

            $logs = ScoreLogModel::where('user_id', $userId)
                ->orderBy('created_at', 'desc')
                ->paginate($pageSize, ['*'], 'page', $page);

            $items = $logs->items();
            foreach($items as &$item){
                $item->created_at_text = date('Y-m-d H:i:s', $item->created_at);
                $item['action_text'] = ScoreLogModel::getActionText($item->action);
            }

            return json([
                'data' => [
                    'list' => $items,
                    'total' => $logs->total(),
                    'current_page' => $logs->currentPage(),
                    'per_page' => $logs->perPage(),
                    'last_page' => $logs->lastPage()
                ],
                'msg' => '获取积分日志成功',
                'code' => 1
            ]);

        }catch(Exception $e){
            return json([
                'data' => null,
                'msg' => $e->getMessage(),
                'code' => 0
            ]);
        }
    }
}
